package com.qianfeng.smartdevices.service.impl;

import com.qianfeng.smartdevices.cache.UserRoleCache;
import com.qianfeng.smartdevices.dto.ResultCode;
import com.qianfeng.smartdevices.event.UserRoleChangeEvent;
import com.qianfeng.smartdevices.exceptions.AddErrorException;
import com.qianfeng.smartdevices.mapper.UserRoleMapper;
import com.qianfeng.smartdevices.pojo.CheckStatus;
import com.qianfeng.smartdevices.pojo.UserRole;
import com.qianfeng.smartdevices.service.UserRoleService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationContext;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;
@Service
@Transactional
public class UserRoleServiceImpl implements UserRoleService {

    private UserRoleMapper userRoleMapper;

    private UserRoleCache userRoleCache;
    private ApplicationContext context;
    @Autowired
    public void setUserRoleCache(UserRoleCache userRoleCache) {
        this.userRoleCache = userRoleCache;
    }
    @Autowired
    public void setContext(ApplicationContext context) {
        this.context = context;
    }

    @Autowired
    public void setUserRoleMapper(UserRoleMapper userRoleMapper) {
        this.userRoleMapper = userRoleMapper;
    }

    @Override
    public void addUserRole(UserRole userRole) {
        if (userRole.isNull(CheckStatus.ADD)) {
            throw new AddErrorException("添加的数据不能为空", ResultCode.DATA_NOT_ALLOW_NUL);
        }
        userRoleMapper.addUserRole(userRole);
        context.publishEvent(new UserRoleChangeEvent());
    }

    @Override
    public List<UserRole> findAllUserRole() {
//        return userRoleMapper.findAllUserRole();
        return userRoleCache.getAllData();
    }

    @Override
    public void updateUserRole(Long userId, Long roleId, Long uid, Long rid) {
        userRoleMapper.updateUserRole(userId,roleId,uid,rid);
        context.publishEvent(new UserRoleChangeEvent());
    }
}
